package com.heima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heima.mapper.PartnerMapper;
import com.heima.pojo.dto.PartnerDTO;
import com.heima.pojo.dto.PartnerQueryDTO;
import com.heima.pojo.entity.TbPartner;
import com.heima.pojo.vo.PartnerVO;
import com.heima.pojo.vo.SkuVO;
import com.heima.pojo.vo.TbSkuPageVO;
import com.heima.service.PartnerService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class PartnerServiceImpl implements PartnerService {
    @Autowired
    private PartnerMapper partnerMapper;
    
    @Override
    public boolean addPartner(PartnerDTO partnerDTO) {
        try {
            TbPartner tbpartner = new TbPartner();
            BeanUtils.copyProperties(partnerDTO, tbpartner);
            tbpartner.setUpdateTime(LocalDateTime.now());
            tbpartner.setCreateTime(LocalDateTime.now());
            tbpartner.setStatus(1);
            
            // 设置默认值
            if (tbpartner.getRatio() == null) {
                tbpartner.setRatio(100);
            }
            
            int result = partnerMapper.addPartner(tbpartner);
            return result > 0;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("添加合作伙伴失败: " + e.getMessage());
        }
    }

    @Override
    public TbSkuPageVO search(PartnerQueryDTO partnerQueryDTO) {
        PageHelper.startPage(partnerQueryDTO.getPageIndex(), partnerQueryDTO.getPageSize());
        List<PartnerVO> records = partnerMapper.search(partnerQueryDTO);
        // 获取分页信息
        Page<PartnerVO> page = (Page<PartnerVO>) records;
        // 构造返回结果
        TbSkuPageVO pageVO = new TbSkuPageVO();
        pageVO.setPageIndex((long) page.getPageNum());
        pageVO.setPageSize((long) page.getPageSize());
        pageVO.setTotalCount(page.getTotal());
        pageVO.setTotalPage((long) page.getPages());
        pageVO.setCurrentPageRecords(records);
        return pageVO;


    }

    @Override
    public PartnerVO getPartnerById(String id) {
        return partnerMapper.getPartnerById(id);

    }

    @Override
    public boolean updatePartner(String id, PartnerDTO partnerDTO) {
        return partnerMapper.updatePartner(id, partnerDTO) > 0;


    }

    @Override
    public boolean deletePartner(String id) {
        return partnerMapper.deletePartner(id) > 0;

    }


}